<?php
namespace app\admin\controller;
use app\model\Images as ImagesModel;
use think\Db;

use app\lib\baidu\DeliApi as baiduApi;


class Images extends Base
{
    public $exception = ['aicompanydetai'];

    public function __construct(){
        $model = new ImagesModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '分类';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function assignFields(){
        $model = $this->model;

        $fields = [
            'image'=>['name'=>'<i class="mdi mdi-camera" style="font-size:20px;"></i> <br />图片上传 ','type'=>'file'],
            'tags'=>['name'=>'标签（以逗号分隔，最多2个）','type'=>'text'],
            'url'=>['name'=>'跳转链接','type'=>'text'],
        ];
        $page_info = $this->page_info;
        if ( in_array($page_info['action'], ['edit']) ) {
            unset($fields['image']);
        }
        $valids = createPageValid($fields);
        $this->assign([
            'fields'=>$fields,
            'valids'=>$valids
        ]);

    }

    public function assignSearchs(){
        $model = $this->model;
        $search_params = [
            [
                ['key'=>'name','name'=>'名称','type'=>'text'],
                ['key'=>'tags','name'=>'标签','type'=>'text'],
                ['key'=>'status','name'=>'状态','type'=>'select1_1','params'=>$model->getStatusList()],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

    public function index(){
        $model = $this->model;
        $map_params = [
            ['key'=>'name','type'=>'like'],
            ['key'=>'status','type'=>'='],
            ['key'=>'tags','type'=>'like'],
        ];
        $map = getSearchParam($map_params);

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',20)
        ];
        // 显示筛选
        $this->assignSearchs();

        $list = $model->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();
        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }

    public function add(){
        $model = $this->model;
        if (request()->isPost()) {
            $fields = [
                'must'=>['image'],
                'nomust'=>['description','brief','tags','url']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            $params = [];
            if (!empty($save_data['brief'])) {
                foreach ($save_data['brief']['name'] as $k => $vo) {
                    $params[$save_data['brief']['name'][$k]] = $save_data['brief']['value'][$k];
                }
            }
            $save_data['brief'] = json_encode($params,JSON_UNESCAPED_UNICODE);

            $image = explode('/',$save_data['image']);
            $save_data['name'] = $image[count($image) - 1];
            $image = explode('.',$save_data['name']);
            // $save_data['name'] = $image[0];
            $save_data['extension'] = $image[count($image) - 1];
            $save_data['ctime'] = time();

            $params['url'] = $save_data['image'];
            $result = (new baiduApi())->imageUpload($save_data['image'],json_encode($params,JSON_UNESCAPED_UNICODE),$params['tags']);
            if ($result['status'] == 0) {
                $save_data['status'] = -1;
                $save_data['remark'] = $result['msg'];
            }else{
                $save_data['status'] = 1;
                $save_data['cont_sign'] = $result['cont_sign'];
            }

            if ( $model->save($save_data) ) {
                $this->success("添加成功",url('index'));
            }else{
                $this->error("添加失败");
            }
        }

        $this->assignFields();
        return view('save', [
            
        ]);
    }

    public function edit(){
        $id = input('id');
        if (empty($id)) { $this->error('id不能为空'); }
        
        $model = $this->model;
        if (request()->isPost()) {
            $fields = [
                'nomust'=>['description','tags','url']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            // $params = [];
            // if (!empty($save_data['brief'])) {
            //     foreach ($save_data['brief']['name'] as $k => $vo) {
            //         $params[$save_data['brief']['name'][$k]] = $save_data['brief']['value'][$k];
            //     }
            // }
            // $save_data['brief'] = json_encode($params,JSON_UNESCAPED_UNICODE);
        }

        return parent::updateData($id,$save_data);
    }

    // 导入
    public function import(){
        set_time_limit ( 0 );
        ini_set('memory_limit','2048M');

        if (request()->isPost()) {
            $model = $this->model;

            $file = $_FILES['file'];
            if (empty($file)) {
                $this->error('未检测到文件');
            }

            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_name']);
            $list=$spreadsheet->getsheet(0)->toArray();   //转换为数组格式

            $titles = $list[0];
            array_shift($list);  //删除第一个数组(标题);

            $group = '11273';

            $results = [];
            foreach ($list as $k => $vo) {
                $brief = [
                    'skuid'=>$vo[0],
                    'g_barcode'=>$vo[1]
                ];
                $tmp = [
                    'id'=>$brief['skuid'],
                    'name'=>$vo[1],
                    'image'=>$vo[3],
                    'description'=>$brief['g_barcode'],
                    'extension'=>pathinfo($vo[3], PATHINFO_EXTENSION),
                    'brief'=>json_encode($brief,JSON_UNESCAPED_UNICODE),
                    'group'=>$group
                ];
                
                if(in_array($tmp['id'],array_column($results, 'id'))){
                    continue;
                }   
                if (Db::name('images')->where('id',$tmp['id'])->value('id') > 0) {
                    continue;
                }

                $results[] = $tmp;
            }

            Db::name('images')->insertAll($results);
            $this->success('导入成功');
        }

        return view('import', [
            
        ]);
    }

    // 导入
    public function importMedias(){
        set_time_limit ( 0 );
        ini_set('memory_limit','2048M');

        if (request()->isPost()) {
            $model = $this->model;

            $file = $_FILES['file'];
            if (empty($file)) {
                $this->error('未检测到文件');
            }

            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_name']);
            $list=$spreadsheet->getsheet(0)->toArray();   //转换为数组格式

            $titles = $list[0];
            array_shift($list);  //删除第一个数组(标题);


            $results = [];
            foreach ($list as $k => $vo) {
                $sku_info = explode(',',$vo[4]);
                if (count($sku_info) > 1) {
                    continue;
                }
                $sku_info = explode('-',$sku_info[0]);
                foreach ($sku_info as $sku_k => $sku_v) {
                    $tmp = explode('：',$sku_v);
                    $sku_info[$sku_k] = $tmp[count($tmp) - 1];
                }

                $sku_info = [
                    'g_barcode'=>$sku_info[0],
                    'num'=>$sku_info[1],
                ];

                $tmp = [
                    'group'=>$vo[0],
                    'upflag'=>$vo[1],
                    'topvideourl'=>$vo[2],
                    'downvideourl'=>$vo[3],
                    'sku_info'=>json_encode($sku_info,JSON_UNESCAPED_UNICODE),
                ];
                if (empty($tmp['topvideourl'])) {
                    continue;
                }
                
                $results[] = $tmp;
                if (count($results) >= 2000) {
                    break;
                }
            }

            Db::name('medias')->insertAll($results);
            $this->success('导入成功');
        }

        return view('import', [
            
        ]);
    }

    public function updateBaidu(){
        set_time_limit ( 0 );
        ini_set('memory_limit','2048M');

        $list = $this->model->where([
            ['status','=',0],
            ['group','=',10824]
        ])->select();
        // dump($list);die;
        foreach ($list as $k => $vo) {
            $params = json_decode($vo['brief'],true);
            $params['url'] = $vo['image'];
            $result = (new baiduApi())->imageUpload($vo['image'],json_encode($params,JSON_UNESCAPED_UNICODE),'');
            if ($result['status'] == 1) {
                $this->model->where('id',$vo['id'])->update([
                    'status'=>1,
                    'cont_sign'=>$result['cont_sign']
                ]);
            }
        }
    }

    public function aiCompanyDetai($name=''){
        set_time_limit ( 0 );
        ini_set('memory_limit','2048M');
        $curtime = time();

        $token = 'pat_98YPb3845yixX5qkIj4U0QcQ9YPrbCFOKvjoy1ohtKtO96dvLTqME2QeIg1Ibi9l';

        $workflow_id = '7526841029410422799';
        $api_url = 'https://api.coze.cn/v1/workflow/run';
        $header = [
            'Content-Type:application/json',
            'Authorization:Bearer '.$token
        ];

        $list = Db::name('medias')->where([
            ['group','=',11273],
            ['status','=',0]
        ])->limit(10)->select();

        foreach ($list as $k => $vo) {
            if (time() - $curtime > 550) {
                exit('finish');
            }
            $sku_info = json_decode($vo['sku_info'],true);

            $result = httpRequest($api_url,json_encode([
                'workflow_id'=>$workflow_id,
                'parameters'=>[
                    'input'=>$vo['topvideourl'],
                    'group'=>$vo['group'],
                ]
            ]),'POST',$header);
            Db::name('test')->insert(['content'=>$vo['id'].'-------']);
            Db::name('test')->insert(['content'=>$result]);

            $result = json_decode($result,true);
            
            
            $data = json_decode($result['data'],true);
            // $is_right = $image['output'] == $sku_info['g_barcode'] ? 1 : -1;

           

            Db::name('medias')->where('id',$vo['id'])->update([
                'status'=>1,
                'coze_ouput'=>$data['output'],
                'img1'=>$data['img1'],
                'img2'=>$data['img2'],
                // 'is_right'=>$is_right,
                // 'search_img'=>Db::name('images')->where('cont_sign',$data['output'])->value('image')
            ]);
        }
        
        
      
    }




   
}
